package com.zjl.学习.第03章_步骤Shop.D_步骤监听器;

import com.zjl.springbatch.util.OutColour;
import org.springframework.batch.core.ChunkListener;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.item.ExecutionContext;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * ClassName: MyChunkListener
 * Package: com.zjl.学习.第03章_步骤Shop.D_步骤监听器
 * Description:
 *
 * @Author 张蛟龙
 * @Create 2024/8/2 22:01
 * @Version 1.0
 */
@Component//放入 bean  块监听
public class MyChunkListener implements ChunkListener {

    @Override//启动前
    public void beforeChunk(ChunkContext chunkContext) {
        long begin = System.currentTimeMillis();
        OutColour.out.printlnYellow("**********************【块侦听器 开始时间】" + begin + "************************");
        ExecutionContext executionContext = chunkContext.getStepContext().getStepExecution().getExecutionContext();
        //获取执行的当前时间
        executionContext.putLong("ChunkBegin", System.currentTimeMillis());
    }

    @Override//启动后
    public void afterChunk(ChunkContext chunkContext) {
        long end = System.currentTimeMillis();
        ExecutionContext executionContext = chunkContext.getStepContext().getStepExecution().getExecutionContext();
        long begin = executionContext.getLong("ChunkBegin");

        OutColour.out.printlnYellow("**********************【块侦听器 开始时间】" + end + "************************");
        OutColour.out.printlnYellow("**********************【整个块侦听器 总耗时间】 " + (end - begin) + "************************");
        System.out.println();
    }

    @Override//异常
    public void afterChunkError(ChunkContext chunkContext) {
        List<Throwable> failureExceptions = chunkContext.getStepContext().getStepExecution().getFailureExceptions();
        for (Throwable throwable : failureExceptions) {
            OutColour.out.printlnRed(throwable);
        }
    }
}
